<template>
    <div class="wrap">
        <!--选择节点、输入station-->
        <div class="operation-border">
            <div>
                <label style="font-size: 14px;font-weight: bold;color: initial;float: left">
                    {{ $t('message.EletronicInfoTool.selectPartNode') }}：
                </label>
                <el-button icon="el-icon-delete"
                           style="margin-right: 5px;float: right"
                           :disabled="this.selectedPartNode.length ===0"
                           @click="removeAllPartNodes()">
                </el-button>
            </div>
            <query-list
                v-model="this.selectedPartNode"
                :description="$t('message.EletronicInfoTool.selectedPartNode')"
                @removeItem="removeSelectedPartNode"
                active = 1>
            </query-list>
            <div class="d-flex align-items-center">
                <label style="font-size: 14px;font-weight: bold;color: initial;">{{
                    $t('message.EletronicInfoTool.inputStation')
                    }}：
                </label>
                <el-input id="station"
                          v-model="station"
                          type="string"
                          step="1"/>
            </div>
            <!--添加至列表 + 取消 -->
            <div class="button-style">
                <el-button type="success" disabled="true">选中的节点共计【{{this.selectedPartNode.length}}】条</el-button>
                <el-button type="primary" size="small"
                           :disabled="!(this.selectedPartNode.length !==0 && this.station!=='')"
                           @click="addToSelection()">
                    {{ $t('message.EletronicInfoTool.addToSelectionList') }}
                </el-button>
                <el-button type="primary" size="small"
                           :disabled="this.selectedPartNode.length !==0 && this.station!==''"
                           @click="nextChoose()">
                    {{ $t('message.EletronicInfoTool.continueChoose') }}
                </el-button>
            </div>
        </div>
        <!--选中节点的列表、单个或批量处理AO信息-->
        <div id="step2">
            <div>
                <div>
                    <div id="left" style="float: left">
                        <el-label
                            style="font-size: 14px;font-weight: bold;color: initial;float: left;margin: 6px 20px 5px 20px;">
                            {{ $t('message.EletronicInfoTool.selectInstallType') }}：
                        </el-label>
                        <el-select
                            v-model="typeValue"
                            :disabled="mode === 2"
                            filterable
                            @change="handleTypeChange"
                            size="medium">
                            <el-option
                                style="font-size: 14px;"
                                v-for="item in typeOptions"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                            </el-option>
                        </el-select>
                    </div>
                    <div class="button-style" style="float: right;margin: 5px 10px 10px 0px;">
                        <!--编辑-->
                        <el-button type="primary"
                                   size="small"
                                   :disabled="(this.tableData.length === 0 || this.mode === 2)"
                                   ref="refEditBtn"
                                   @click="editSelectionData">
                            {{ $t('message.EletronicInfoTool.edit') }}
                        </el-button>
                        <!--保存-->
                        <el-button type="primary"
                                   size="small"
                                   :disabled="mode !== 2"
                                   @click="saveSelectionData">
                            {{ $t('message.EletronicInfoTool.save') }}
                        </el-button>
                        <!--取消-->
                        <el-button type="primary"
                                   size="small"
                                   :disabled="mode !== 2"
                                   ref="refDeleteBtn"
                                   @click="cancelSelectionData">
                            {{ $t('message.EletronicInfoTool.cancel') }}
                        </el-button>
                    </div>
                </div>
                <el-table ref="selectionList"
                          :data="tableData"
                          highlight-current-row
                          @current-change="handleCurrentChange"
                          @selection-change="handleSelectionChange"
                          @row-dblclick="handleRowDoubleClick"
                          tooltip-effect="dark"
                          style="width: 100%;margin-top: 5px"
                          border size="small"
                          max-height="300px"
                          v-bind:style="{ height: tableData.length?'300px' : '100px' }">
                    <!--复选框-->
                    <el-table-column
                            type="selection"
                            width="40">
                    </el-table-column>
                    <!--序号-->
                    <!--                    <el-table-column prop="index"-->
                    <!--                                     min-width="40"-->
                    <!--                                     :label="$t('message.EletronicInfoTool.serialNumber')">-->
                    <!--                        <template v-slot="scope">-->
                    <!--                            <label class="label">{{ scope.row.index + 1 }}</label>-->
                    <!--                        </template>-->
                    <!--                    </el-table-column>-->
                    <!--选中节点-->
                    <el-table-column prop="selectedPartNodeName"
                                     header-align="center"
                                     :label="$t('message.EletronicInfoTool.selectedPartNode')"
                                     min-width="180">
                        <template v-slot="scope">
                            <label class="label" style="font-size: 13px">{{ scope.row.partNodeName }}</label>
                        </template>
                    </el-table-column>
                    <!--工位号-->
                    <el-table-column prop="station"
                                     head-align="center"
                                     :label="$t('message.EletronicInfoTool.station')"
                                     min-width="60"
                                     :filters="stationFilters"
                                     :filter-method="filterHandler">
                        <template v-slot="scope">
                            <label class="label" style="font-size: 13px">{{ scope.row.station }}</label>
                        </template>
                    </el-table-column>
                    <!--AO Number-->
                    <el-table-column prop="AONumber"
                                     header-align="center"
                                     :label="$t('message.EletronicInfoTool.AONumber')"
                                     min-width="80"
                                     :filters="aoNumberFilters"
                                     :filter-method="filterHandler">
                        <template v-slot="scope">
                            <label class="label" style="font-size: 13px">{{ scope.row.aoNumber }}</label>
                        </template>
                    </el-table-column>
                    <!--AO Name-->
                    <el-table-column prop="AOName"
                                     header-align="center"
                                     :label="$t('message.EletronicInfoTool.AOName')"
                                     min-width="80"
                                     :filters="aoNameFilters"
                                     :filter-method="filterHandler">
                        <template v-slot="scope">
                            <label class="label" style="font-size: 13px">{{ scope.row.aoName }}</label>
                        </template>
                    </el-table-column>
                    <!--ElectrialBondingType-->
                    <el-table-column prop="ElectrialBondingType"
                                     header-align="center"
                                     :label="$t('message.EletronicInfoTool.ElectrialBondingType')"
                                     min-width="80"
                                     :filters="electrialBondingTypeFilters"
                                     :filter-method="filterHandler">
                        <template v-slot="scope">
                            <label class="label" style="font-size: 13px">{{ scope.row.electricalBondingType }}</label>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div class="operation-border" v-if=" mode === 2">
                <!--输入AO号-->
                <div class="d-flex align-items-center">
                    <label class="label-style">{{ $t('message.EletronicInfoTool.inputAONumber') }}：</label>
                    <el-input id="AONumber"
                              ref="refAONumber"
                              v-model="AONumber"
                              type="string"
                              step="1"/>
                </div>
                <!--输入AO名称-->
                <div class="d-flex align-items-center">
                    <label class="label-style">{{ $t('message.EletronicInfoTool.inputAOName') }}：</label>
                    <el-input id="AOName"
                              ref="refAOName"
                              v-model="AOName"
                              type="string"
                              step="1"/>
                </div>
                <!--输入ElectricalBondingType-->
                <div class="d-flex align-items-center">
                    <label class="label-style">{{ $t('message.EletronicInfoTool.inputElectricalBondingType') }}：</label>
                    <el-input id="ElectricalBondingType"
                              v-model="ElectricalBondingType"
                              type="string"
                              step="1"/>
                </div>
            </div>
        </div>
        <leak-item-list
            :dialog-msg="dialogMsg"
            :dialog-visible="showLeakItemListDialog"
            :omitted-table-data="omittedTableData"
            @confirm-dialog="forceExport"
            @close-dialog="closeDialog"/>
        <!-- 确认和关闭-->
        <div class="btn">
            <el-button
                type="success" disabled="true">
                共计【{{ this.tableData.length }}】条
            </el-button>
            <el-button
                    type="primary"
                    size="small"
                    :disabled="this.tableData.length === 0 || (this.mode !== 3 && this.mode !== 0)"
                    @click="confirm">
                {{ $t('message.EletronicInfoTool.export') }}
            </el-button>
            <el-button
                    type="primary"
                    size="small"
                    @click="close">
                {{ $t('message.EletronicInfoTool.close') }}
            </el-button>
        </div>
    </div>
</template>

<script>
import DialogMixin from "../DialogMixin";
import {electricalCommand} from "../../../command/ElectricalCommand";
import LeakItemList from "./CmdDlgLeakItemList.vue";

export default {
    mixins: [DialogMixin],
    name: 'CmdDlgEletronicInfoOutput',
    components:{LeakItemList},
    data() {
        return {
            //ui绑定
            selectedPartNode: [], //选中节点 显示名称
            station: '', //station
            typeOptions: [
                {
                    value: 'AllPart',
                    label: this.$t('message.EletronicInfoTool.AllPart'),
                },
                {
                    value: 'ConnectorFasteningPart',
                    label: this.$t('message.EletronicInfoTool.ConnectorFasteningPart'),
                },
                {
                    value: 'GroundingPart',
                    label: this.$t('message.EletronicInfoTool.GroundingPart'),
                },
                {
                    value: 'ProtectionMaterialForHoleEdging',
                    label: this.$t('message.EletronicInfoTool.ProtectionMaterialForHoleEdging'),
                },
                {
                    value: 'WireSupportingPart',
                    label: this.$t('message.EletronicInfoTool.WireSupportingPart'),
                },
                {
                    value: 'SPAClampPart',
                    label: this.$t('message.EletronicInfoTool.SPAClampPart'),
                },
                {
                    value: 'ClampPart',
                    label: this.$t('message.EletronicInfoTool.ClampPart'),
                },
                {
                    value: 'SealingFittingPart',
                    label: this.$t('message.EletronicInfoTool.SealingFittingPart'),
                },
                {
                    value: 'RelaySocketPart',
                    label: this.$t('message.EletronicInfoTool.RelaySocketPart'),
                },
                {
                    value: 'TerminalBoardPart',
                    label: this.$t('message.EletronicInfoTool.TerminalBoardPart'),
                },
                {
                    value: 'ElectricalHarnessSeparator',
                    label: this.$t('message.EletronicInfoTool.ElectricalHarnessSeparator'),
                },
                {
                    value: 'AdhesiveHarnessMountPart',
                    label: this.$t('message.EletronicInfoTool.AdhesiveHarnessMountPart'),
                },
                {
                    value: 'ModuleRailPart',
                    label: this.$t('message.EletronicInfoTool.ModuleRailPart'),
                },
                {
                    value: 'WireHarnessStiffenerTubePart',
                    label: this.$t('message.EletronicInfoTool.WireHarnessStiffenerTubePart'),
                },
                {
                    value: 'MountPart',
                    label: this.$t('message.EletronicInfoTool.MountPart'),
                },
                {
                    value: 'InLineSpliceRectangleConnectorHousingPart',
                    label: this.$t('message.EletronicInfoTool.InLineSpliceRectangleConnectorHousingPart'),
                },
                {
                    value: 'OtherPart',
                    label: this.$t('message.EletronicInfoTool.OtherPart'),
                },
                // {
                //     value: 'OtherAO',
                //     label: 'OtherAO',
                // },
                // {
                //     value: 'GeneralInformation',
                //     label: 'GeneralInformation',
                // }
            ],
            typeValue: 'AllPart',
            AONumber: '',
            AOName: '',
            ElectricalBondingType: '',
            tableData: [], //表格绑定数据
            allTableData: [],//保存后的所有数据
            checkedList: [], //表格中勾选的行
            phidVersionNumber: 1,
            //exportData: [],//最终需要导出的
            //selectRow:[],

            //状态控制
            //selectionListLoad: false, //列表加载
            mode: 0,//0-初始状态-不可导出 1-新增 2-修改 3保存后可导出
            //missFlag: false,//是否存在遗漏项 默认 不
            omittedTableData: [],//遗漏零件数据
            showLeakItemListDialog: false, //是否显示遗漏项，true时代表有遗漏
            dialogMsg: '',//弹框提示的数量信息
            ifForceExport: false,//是否强制导出

            //过滤用
            stationFilters: [],
            aoNumberFilters: [],
            aoNameFilters: [],
            electrialBondingTypeFilters: [],

        };
    },
    mounted() {
        electricalCommand.init(1000, 800, 1200, () => {
            electricalCommand.pickAssemblyAndPartInstances(async (instanceArr) => {
                if (instanceArr.length > 0) {
                    //根据当前选中装配id去找下面所有的零件进行显示
                    let insArr = [];
                    instanceArr.forEach(item => {
                        insArr.push(item?.id);
                    })
                    this.selectedPartNode = await electricalCommand.getInsChildren(insArr);
                    instanceArr.forEach(item =>{
                        if (item.type === 'assembly') {
                            if (!this.selectedPartNode?.find(node => node.id === item.id)) {
                                this.selectedPartNode.push(item);
                            }
                        }
                    })
                    //TODO 取消选中后的再次选中
                }
            })
        });
    },
    watch: {
        allTableData() {
            this.tableData = this.allTableData;
            this.setFilters();
        },
        tableData(){
            // //设置已经加入列表的节点隐藏
            // let insIds = [];
            // this.tableData.forEach(rowData =>{
            //     insIds.push(rowData.instanceId);
            // })
            // electricalCommand.setInstanceInvisible(insIds);
        },
        typeValue(){
            if(this.typeValue === 'AllPart'){
                this.tableData = this.allTableData;
            }
        },
    },
    methods: {
        //适配UI高度
        changePluginContainerHeight() {
            electricalCommand.changePluginContainerHeight({
                minWidth: this.$el.clientWidth + 50,
                maxHeight: this.$el.clientHeight,
                width: 1000
            });
        },
        //移除所有选中节点
        removeAllPartNodes() {
            this.selectedPartNode = [];
            electricalCommand.clearAllSelectedInstances();
            this.station = '';
        },
        //移除选中节点
        removeSelectedPartNode(item) {
            let params = [item.id];
            electricalCommand.clearHighLightInstances(params);
        },
        //确认
        async confirm() {
            //校验是否都输入了station及AO信息
            let res = this.allTableData
                .some(obj => [obj.station, obj.aoName, obj.aoNumber, obj.electricalBondingType]
                    .some(value => value === '' || value === null || value === undefined));
            if (res) {
                electricalCommand.eventBusAlertMsg(this.$t('message.EletronicInfoTool.aoInfoCheckMsg'), 'warning');
                return;
            }
            await this.leakageItemsCheck();

            if (!this.showLeakItemListDialog || this.ifForceExport) {
                this.exportXML();
            }

            //console.log(this.allTableData);
            //console.log(this.allTableData.filter(item => item.installType === 'R'));

            //this.close();
        },
        //关闭
        close() {
            //关闭前设置所有隐藏的全部显示出来
            this.setAllInstancesVisible();
            electricalCommand.closeActiveCmd();
        },
        //将选中的节点加入列表
        addToSelection() {
            if (!this.station) {
                electricalCommand.eventBusAlertMsg(this.$t('message.EletronicInfoTool.inputStation'), 'warning');
                return;
            }
            if (this.selectedPartNode.length > 0) {
                //判断是否重复，重复的节点不进行添加
                const tableDataSet=new Set();
                this.allTableData.forEach(item=>{
                    tableDataSet.add(item.partNodeName);
                })
                this.selectedPartNode = this.selectedPartNode.filter(item => !tableDataSet.has(item.name));
                if (this.selectedPartNode.length === 0) {
                    return;
                }
                //批量获取类型
                electricalCommand.batchDealSelectedNodes(this.selectedPartNode, res => {
                    //批量设置station
                    res.forEach(item=>{
                        item.station = this.station;
                    })
                    //设置实例隐藏
                    this.setInstanceVisibility(res, false);
                    this.allTableData.push(...res);
                    electricalCommand.eventBusAlertMsg(this.$t('message.EletronicInfoTool.addToListSuccess'), 'success');
                })
            }
        },
        //选中一行数据的时候执行
        handleCurrentChange(currentRow, oldCurrentRow) {
            // if (val) {
            //     this.selectRow = val;
            // }
        },
        //选择项发生变化时触发
        handleSelectionChange(val) {
            if (val) {
                this.checkedList = val;
            }
        },
        //双击某一行 自动触发选中当前行
        handleRowDoubleClick(row,column,event){
            this.$refs.selectionList.toggleRowSelection(row,true);
        },
        //编辑
        editSelectionData() {
            //编辑之前校验是否已经选择类型
            if (this.typeValue === '') {
                electricalCommand.eventBusAlertMsg(this.$t('message.EletronicInfoTool.noSelectTypeWarnMsg'), 'warning');
                return;
            }
            //编辑之前校验是否勾选了行
            if (this.checkedList.length === 0) {
                electricalCommand.eventBusAlertMsg(this.$t('message.EletronicInfoTool.editWarnMsg'), 'warning');
                return;
            }
            this.mode = 2; //编辑状态
            this.$nextTick(() => {
                this.$refs.refEditBtn.$el.blur();
                this.$refs.refAONumber.$el.focus();
            });
        },
        //保存
        saveSelectionData() {
            //校验输入是否为空、是否合法
            if (!this.AONumber) {
                electricalCommand.eventBusAlertMsg(this.$t('message.EletronicInfoTool.inputAONumber'), 'warning');
                return;
            }
            if (!this.AOName) {
                electricalCommand.eventBusAlertMsg(this.$t('message.EletronicInfoTool.inputAOName'), 'warning');
                return;
            }
            // if (!this.ElectricalBondingType) {
            //     electricalCommand.eventBusAlertMsg(this.$t('message.EletronicInfoTool.inputElectricalBondingType'), 'warning');
            //     return;
            // }
            //需要区别是单条应用还是批量应用，单条的应用单条，批量的批量设置
            //获取选中的行
            this.checkedList.forEach(row => {
                row.aoNumber = this.AONumber;
                row.aoName = this.AOName;
                row.electricalBondingType = this.ElectricalBondingType;
                //row.station = this.station;
                //row.installType = this.typeValue;
            })
            //设置状态
            this.mode = 3;
            this.resetData();
            this.setFilters();
        },
        //继续选择
        nextChoose(){
            //清除上一次选中的节点
            this.removeAllPartNodes();
            //清除上一次输入的工位号
            this.station = '';
        },
        //取消
        cancelSelectionData() {
            this.mode = 0;
        },
        //清除表格中选中
        clearTableChecked() {
            this.$refs.selectionList.clearSelection();
        },
        //类型切换
        handleTypeChange(val) {
            if (val === 'AllPart') {
                this.tableData = this.allTableData;
            } else {
                this.tableData = this.allTableData.filter(row => row.installType === val);
            }
        },
        //恢复初始值
        resetData() {
            //清空勾选
            this.clearTableChecked();
            //清空下拉选项
            this.typeValue = 'AllPart';
            //清空控件值
            this.AONumber = '';
            this.AOName = '';
            this.ElectricalBondingType = '';
        },
        //生成三位数的DMVersion
        generatePHIDVersionStr() {
            let phidVer = this.phidVersionNumber.toString();
            if (phidVer.length === 1) {
                return '00' + phidVer;
            } else {
                return '0' + phidVer;
            }
        },

        //设置拾取实例时只能拾取装配类型的，
        checkSelectedInstance(instances) {
            let flag = true;
            instances.forEach(ins => {
                if (ins.type === 'part') {
                    flag = false;
                }
            });
            return flag;
        },
        //合并数组并去重
        mergeAndDedupeObjectArrays(arr1, arr2) {
            const combinedArray = arr1.concat(arr2);
            const uniqueMap = new Map();
            const result = [];
            combinedArray.forEach((obj) => {
                const id = obj.id;
                if (!uniqueMap.has(id)) {
                    uniqueMap.set(id, true);
                    result.push(obj);
                }
            });
            return result;
        },
        //设置所有选中的全部 显示
        setAllInstancesVisible() {
            let insIds = [];
            this.tableData.forEach(rowData => {
                insIds.push(rowData.instanceId);
            })
            electricalCommand.setInstanceVisible(insIds);
        },
        //防漏项检查
        async leakageItemsCheck() {
            let expectedIns = await electricalCommand.getCurrentAssemblyFlattenTree();
            let actualIns = this.allTableData;
            if(expectedIns.length === actualIns.length){
                //数量相等，不弹框
                this.ifForceExport = true;
            }else {
                this.omittedTableData = expectedIns.filter(itemA => !actualIns.some(itemB => itemB.instanceId === itemA.id));
                this.showLeakItemListDialog = true;
                this.dialogMsg = '应选【' + expectedIns.length + '】条，已选【' + actualIns.length + '】条，遗漏【' + this.omittedTableData.length + '】条';
            }
        },
        //实际的导出逻辑
        exportXML(){
            electricalCommand.openLoading(this.$t('message.EletronicInfoTool.isExporting'));
            let exportInparam = {
                xmlSourceVersion: this.generatePHIDVersionStr(),
                selectionList: this.allTableData,
                assemblyDocId: '',
                activeVerionId: '',
            }
            electricalCommand.getElectricalPropertyXML(exportInparam, res => {
                let xmlData = res;
                if (xmlData) {
                    this.xmlContent = xmlData;
                    let blob = new Blob([this.xmlContent], {type: 'application/xml'});
                    let link = document.createElement('a');
                    link.href = URL.createObjectURL(blob);
                    link.download = '电气属性导出.xml';
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);
                } else {
                    electricalCommand.eventBusAlertMsg(this.$t('message.EletronicInfoTool.getXMLDataErrorMsg'), 'warning');
                }
            })
            this.phidVersionNumber++;
            electricalCommand.closeLoading();
            electricalCommand.eventBusAlertMsg(this.$t('message.EletronicInfoTool.exportSuccess'),'success');
        },
        //强制导出
        forceExport(){
            this.ifForceExport =true;
            this.exportXML();
            this.showLeakItemListDialog = false;
            this.ifForceExport = false;//必须重置
        },
        //关闭对话框
        closeDialog() {
            this.showLeakItemListDialog = false;
        },
        //设置列的过滤
        setFilters(){
            this.setStationFilters();
            this.setAONumberFilters();
            this.setAONameFilters();
            this.setElectrialBondingTypeFilters();
        },
        setStationFilters() {
            const arrs = [...new Set(this.tableData.map(item => item.station))];
            this.stationFilters = arrs.map(station => ({text: station, value: station}));
        },
        setAONumberFilters() {
            const arrs = [...new Set(this.tableData.map(item => item.aoNumber))];
            this.aoNumberFilters = arrs.map(aoNumber => ({text: aoNumber, value: aoNumber}));
        },
        setAONameFilters() {
            const arrs = [...new Set(this.tableData.map(item => item.aoName))];
            this.aoNameFilters = arrs.map(aoName => ({text: aoName, value: aoName}));
        },
        setElectrialBondingTypeFilters() {
            const arrs = [...new Set(this.tableData.map(item => item.electricalBondingType))];
            this.electrialBondingTypeFilters = arrs.map(electricalBondingType => ({
                text: electricalBondingType,
                value: electricalBondingType
            }));
        },
        //列的筛选
        filterHandler(value, row, column) {
            if (column.property === 'AONumber') {
                return row.aoNumber === value;
            } else if (column.property === 'AOName') {
                return row.aoName === value;
            } else if (column.property === 'ElectrialBondingType') {
                return row.electricalBondingType === value;
            } else if (column.property === 'station') {
                return row.station === value;
            }
        },
        //设置列表中数据隐藏
        setInstanceVisibility(selectedNodes, ifVisible) {
            let insIds = [];
            //将加入列表的节点隐藏
            selectedNodes.forEach(rowData => {
                insIds.push(rowData.instanceId);
            })
            if (ifVisible) {
                electricalCommand.setInstanceVisible(insIds);
            } else {
                electricalCommand.setInstanceInvisible(insIds);
            }
        }
    },
};
</script>
<style scoped>
.wrap {
    font-size: 12px;
}

.operation-border {
    border: 2px solid var(--bg-color3);
    padding: 8px;
}

.button-style {
    display: flex;
    justify-content: flex-end;
    margin-top: 5px;
}

.label-style {
    font-size: 13px;
    color: #606266;
    line-height: 30px;
}
</style>
